(function(app){
	app
		.controller("content_15_businessTbrCtrl",["$scope","$state","myFactory",'$stateParams',"$q",'$timeout','$location','$http','$ionicHistory',function($scope,$state,myFactory,$stateParams,$q,$timeout,$location,$http,$ionicHistory){
			//接收参数
			var itemId = $stateParams.itemId;//变更项目ID
			var chdrnum01 =  $stateParams.chdrnum01; //保单号
			var chdrcoy = $stateParams.chdrcoy; //保单公司号码
			var item15 = $stateParams.item15;
			var token=sessionStorage.getItem("token");
			$scope.data = {
		        defaultData : [
		          {
		            text: 'Parent 1',
		            href: '#parent1',
		            tags: ['4'],
		            nodes: [
		              {
		                text: 'Child 1',
		                href: '#child1',
		                tags: ['2'],
		                nodes: [
		                  {
		                    text: 'Grandchild 1',
		                    href: '#grandchild1',
		                    tags: ['0']
		                  },
		                  {
		                    text: 'Grandchild 2',
		                    href: '#grandchild2',
		                    tags: ['0']
		                  }
		                ]
		              },
		              {
		                text: 'Child 2',
		                href: '#child2',
		                tags: ['0']
		              }
		            ]
		          },
		          {
		            text: 'Parent 2',
		            href: '#parent2',
		            tags: ['0']
		          },
		          {
		            text: 'Parent 3',
		            href: '#parent3',
		             tags: ['0']
		          },
		          {
		            text: 'Parent 4',
		            href: '#parent4',
		            tags: ['0']
		          },
		          {
		            text: 'Parent 5',
		            href: '#parent5'  ,
		            tags: ['0']
		          }
		        ]
			};
			
			myFactory.loadingShow();//显示加载圈
			var changeItem15_increment = sessionStorage.getItem("changeItem15_increment");
			var token=sessionStorage.getItem("token");
			var timestamp=myFactory.getTimetamp();
			var sfis= "token-timestamp";
			var signStr="token="+token+"&timestamp="+timestamp;//encodeURI(name)
			var sign = myFactory.hex(signStr);
			var params15Map={
					"itemId":itemId,
					"itemStr":item15,
					"changeItem15_increment":changeItem15_increment
					};
			$http({
				method: 'post',
				url: app.domain + 'input/saveContentItem15.action',
				data:{paramsMap:params15Map,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
			}).then(function successCallback(response) {
				if (response.data.success) {
					itemData=response.data.data.itemData;
					$scope.item15=itemData.item15;
					$scope.item15_b=itemData;
				}
				myFactory.loadingHide();
			}, function errorCallback(response) {
				myFactory.loadingHide();
				myFactory.alert("","初始化失败，请返回重试!","info");
			});
			/*var sfis= "itemId-token-timestamp";
			var signStr="itemId="+"15"+"&token="+token+"&timestamp="+timestamp;
			var sign = myFactory.hex(signStr);
            $scope.readFlag = false;
			$http({
				method: 'GET',
				url: app.domain + 'input/saveContentItem15.action',
				params: {'itemId': itemId,'itemStr':item15,'changeItem15_increment' : changeItem15_increment,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp}
			}).then(function successCallback(response) {
				if (response.data.success) {
					itemData=response.data.data.itemData;
					$scope.item15=itemData.item15;
					$scope.item15_b=itemData;
				}
				myFactory.loadingHide();
			}, function errorCallback(response) {
				myFactory.loadingHide();
				myFactory.alert("","初始化失败，请返回重试!","info");
			});*/

			//职业选择		
			$scope.professionChose = function(){
				modal('open','profession_model','overwindow');
				$('#treeview').treeview({
		          levels: 1,
		          data: $scope.data.defaultData
		        });
			}
			$scope.professionClose = function(){
				modal('close','profession_model','overwindow');
			}

			//返回上一页
			$scope.goBack = function(){
				myFactory.goBack();
			}

			//关闭遮罩
			$scope.overwindowClose = function(){
				$(".overwindow").hide();
				$(".overmodal").hide();
			}


			//公共变量定义
			var _problemId = "" ;	//	题库编号
			var _role	= "" ;		//	答题人角色（投保人、被保人）
			var _typeHealth   = "h";	//	告知类型：健康告知
			var _typeAccount  = "a";	//	告知类型：财务告知
			var _typeBusiness = "b";	//	告知类型：职业告知
			var _splitSign = "|";		//	分割符号，用于组装多个数据元素


			//	保存金额信息
			$scope.saveBusinessBase = function(problemId,role){
			//function saveBusinessBase(problemId,role){
				_problemId = problemId ;
				_role	   = role;
				var _content   = $("#b_" +role+ "_"+_problemId).val();
				if('1'==_problemId){
					if("" == _content){
						myFactory.alert('','请填写工作单位！','info');
						return false;
					}
				}
				if('2'==_problemId){
					if("" == _content){
						myFactory.alert('','请填写工作内容！','info');
						return false;
					}
				}
				//	保存告知信息
				saveNotifyData(_typeBusiness,"Y",_content);
			}

            //	保存职务信息(职务、职业代码、职业等级)
			$scope.saveBusinessInfo = function(role){
			//function saveBusinessInfo(role){
				_role	   = role;
				//	职务名称
				var _busiName = $("#b_" +role+ "_3").val();
				if("" == _busiName){
					myFactory.alert('','请填写职务！','info');
					return false;
				}
				_problemId = "3" ;
				saveNotifyData(_typeBusiness,"Y",_busiName);

				//	职务代码
				var _busiCode = $("#b_" +role+ "_4").val();
				_problemId = "4" ;
				saveNotifyData(_typeBusiness,"Y",_busiCode);

				//	职务等级
				var _busiGrade = $("#b_" +role+ "_5").val();
				_problemId = "5" ;
				saveNotifyData(_typeBusiness,"Y",_busiGrade);
			}

			$scope.openBusiness = function(role){
				modal('open','businessModel','overwindow');
				$scope.busiInfoDataNew="";
				$("#input_search").val("");
				/*$('#treeview').treeview({
					levels: 1,
					data: $scope.data.defaultData
				});*/
				//var busiInfoJson = eval($scope.item15_b.busiInfo);
				//nativesJson={"label": "叙利亚 Syria","val": "SYR"};
				//$scope.regionData = [];
				//$scope.busiInfoData=busiInfoJson;
			}
			$scope.closeBusiness = function(){
				modal('close','businessModel','overwindow');
			}

			$scope.searchBusiness = function(){
				var input_search   = $("#input_search" ).val().trim();
				if(input_search==''){
					myFactory.alert('','请输入职务代码或者职务名称！','info');
					return false;
				}
				var busiInfoJson = eval($scope.item15_b.busiInfo);
				//nativesJson={"label": "叙利亚 Syria","val": "SYR"};
				//$scope.regionData = [];
				var busiInfoJsonNew=[];
				var k=0;
				for(var i = 0; i<busiInfoJson.length; i++){
					var valId=busiInfoJson[i].val;
					var labelVal=busiInfoJson[i].label;
					if(valId.indexOf(input_search) > -1 || labelVal.indexOf(input_search) > -1 || labelVal.indexOf(input_search.toUpperCase()) > -1){
						//var busiInfoJsonNew={"label": labelVal,"val": valId};
						busiInfoJsonNew[k]={
							"label" : labelVal,
							"val" : valId
						};
						k++;
						//$scope.busiInfoDataNew=busiInfoJsonNew;
						//break;
					}else{

					}

					/*if(i==3){
						alert(busiInfoJson[i].val);
						alert(busiInfoJson[i].label);
						break;
					}
					if( src.indexOf( wineTypes[i].value ) > -1 ){
						wineTypes[i].checked = true ;
					}else{
						wineTypes[i].checked = false ;
					}*/

				}
				if(busiInfoJsonNew.length==0){
					myFactory.alert('','没有可匹配的职务代码，请重新输入关键字！','info');
				}else{
					$scope.busiInfoDataNew=busiInfoJsonNew;
				}
				//var busiInfoJsonNew={"label": "叙利亚 Syria","val": "SYR"};
				/*var busiInfoJsonNew=[];
				busiInfoJsonNew[0]={
					"label" : '叙利亚 Syria',
					"val" : 'SYR'
				};

				$scope.busiInfoDataNew=busiInfoJsonNew;*/

			}

			$scope.businessClick = function (role,val,label) {
				//$("#newCity").val(val);
				//$("#newCityCode").val(label);
				console.log("val:"+val+",label:"+label);
				var _val = val;		//	职务代码 + 职业等级
				if (_val != "") {
					var _name = label;
					var vals = _val.split(','); //	把职务代码与职务等级安装切割符号','分开
					$("input[name='b_"+role+"_3']").val(_name);		//	职务名称
					$("input[name='b_"+role+"_4']").val(vals[0]);	//	职务代码
					$("input[name='b_"+role+"_5']").val(vals[1]);	//	职务等级

					$scope.saveBusinessInfo('ow');
				}
			}

			/**
			 * 保存数据到后台
			 * type - 告知类型 (H-健康告知,A-财务告知,B-职业告知)
			 * flag - 答题状态位（是、否）
			 * content - 答题内容
			 **/
			function saveNotifyData(_type,_flag,_content){
				var ret = false;
				var returnFlag="";
				//	对字符串编码
				var deContent = encodeURI(_content);
				/*jQuery.ajax({
				 type:"post",
				 url:basePath+"/common/saveNotify.action",
				 data:param,
				 async:true,
				 dataType:"JSON",
				 success:function(data){
				 if(data == "fail"){
				 ret = true;
				 }
				 }
				 });*/
				var timestamp=myFactory.getTimetamp();
				var sfis= "type-problemId-role-flag-token-timestamp";
				var signStr="type="+_type+"&problemId="+_problemId+"&role="+_role+"&flag="+_flag+"&token="+token+"&timestamp="+timestamp;//encodeURI(name)
				var sign = myFactory.hex(signStr);
				var param = {'type':_type,'problemId':_problemId,'role':_role,'flag': _flag,'content':deContent,'sign':sign,'sfis':sfis,'token':token,'timestamp':timestamp};
				$http({
					method: 'GET',
					url: app.domain + 'common/saveNotify15.action',
					params: param
				}).then(function successCallback(response) {
					if (response.data.success) {
						returnFlag = response.data.data.returnFlag;
						if(returnFlag == "fail"){
							ret = true;
						}
					}
				}, function errorCallback(response) {
					$.alert({
						title: '',
						text: '查询失败!',
						onOK: function () {
						}
					});
				});

				return ret;
			}

			//保存按钮：保存数据[主要为选择“是”弹出的输入框数据保存方法]
			$scope.saveBusinessData = function(){
				var b_ow_1   = $("#b_ow_1" ).val().trim();
				if("" == b_ow_1){
					myFactory.alert('','请填写工作单位！','info');
					return false;
				}

				var b_ow_2   = $("#b_ow_2" ).val().trim();
				if("" == b_ow_2){
					myFactory.alert('','请填写工作内容！','info');
					return false;
				}

				var b_ow_3   = $("#b_ow_3" ).val().trim();
				if(''==b_ow_3){
					myFactory.alert('','请填写职务名称！','info');
					return false;
				}

				//成功保存
				$.alert({title: '',text: '保存成功',onOK: function () {
					//点击确定才返回上一页
					myFactory.goBack();
				}
				});
			}

		}]);        
})(app)